package cn.ekuma.pos.pda.sale.table;

import java.util.ArrayList;
import java.util.List;

import cn.ekuma.android.ui.tree.TreeElement;
import cn.ekuma.data.dao.bean.I_Category;
import cn.ekuma.data.ui.android.BaseBeanCategorySelecter;
import cn.ekuma.data.ui.android.OnBaseBeanSelectedListener;
import cn.ekuma.epos.android.adapter.ProductCategoryAdapter;
import cn.ekuma.epos.datalogic.DataLogicPDA;
import cn.ekuma.epos.datalogic.I_DataLogicSales;
import cn.ekuma.pos.android.pos.R;
import cn.ekuma.pos.pda.sale.TicketManager;

import com.openbravo.bean.Product;
import com.openbravo.bean.ProductCategory;
import com.openbravo.data.basic.BasicException;
import com.openbravo.pos.bean.ProductExt;

import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.os.Message;
import android.util.AttributeSet;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AbsListView.OnScrollListener;
import android.widget.AdapterView.OnItemClickListener;

public class TicketSaleTableProductsPanel extends LinearLayout implements OnBaseBeanSelectedListener<ProductCategory>,OnItemClickListener{

	public TicketSaleTableProductsPanel(Context context, AttributeSet attrs) {
		super(context, attrs);
		init(context);
	}

	private View mainView;
	BaseBeanCategorySelecter catagorytree;
	private ProductCategoryAdapter treeAdapter;
	private GridViewAdapter productAdapter;
	public static final int MSG_LOAD_CATEGORY=1;
	public static final int MSG_FAILURE=0;
	public static final int MSG_LOAD_PRODUCT=2;

	private List<ProductExt> listProducts;
	private GridView products;
	
	OnBaseBeanSelectedListener<Product> productSelectedListener;
	private FrameLayout contentLayout;
	private ImageButton zoomImgBtn;
	
	private void init(Context context) {
		 mainView = LayoutInflater.from(context).inflate( 
             R.layout.table_pos_products, this); 
		 LinearLayout  catagorytreeContent=(LinearLayout) this.findViewById(R.id.catagoryList);
		 products=(GridView) this.findViewById(R.id.gridView1);
		 
		 contentLayout = (FrameLayout) findViewById(R.id.products_contentPanel);
		 //initializeData();  
 
		 catagorytree=new BaseBeanCategorySelecter<ProductCategory>(context);
		 catagorytreeContent.addView(catagorytree);
		 treeAdapter=new ProductCategoryAdapter(context);
		 catagorytree.setAbstractBaseBeanTreeAdapter(treeAdapter);  
		 catagorytree.setOnBaseBeanSelectedListener(this);

		 productAdapter=new GridViewAdapter(context);
		 products.setAdapter(productAdapter);
		 products.setOnItemClickListener(this);
		 
		 zoomImgBtn=new ImageButton(context);
		 zoomImgBtn.setImageResource(R.drawable.tree_collapse);
		 
			
			FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);  
			//此处相当于布局文件中的Android:layout_gravity属性   
			lp.gravity = Gravity.BOTTOM|Gravity.RIGHT;  
			contentLayout.addView(zoomImgBtn,lp);
		 
	}
	
	Handler mSuperHandler;
	public void onLoadData(final Handler mHandler){
		mSuperHandler=mHandler;
		new Thread(){
			@Override
			public void run(){
				I_DataLogicSales dlSales=DataLogicPDA.getDLSales();
				try {
					java.util.List<ProductCategory> catagorys = dlSales.listWithClassName(ProductCategory.class.getName());
					//List<ProductCategory> hotCatagorys=dlSales.
					List<ProductExt> shardProducts=dlSales.listPosShardProducts();
					List<TreeElement> elements=buildTree(catagorys);
					mHandler1.obtainMessage(MSG_LOAD_CATEGORY,elements).sendToTarget();
					mHandler1.obtainMessage(MSG_LOAD_PRODUCT,shardProducts).sendToTarget();//获取图片失败
				} catch (BasicException e) {
					mHandler.obtainMessage(TicketManager.MSG_FAILURE).sendToTarget();//获取图片失败   
				}
			}
			}.start();
	}
	
	 private List<TreeElement> buildTree(List<ProductCategory> catagorys){
	    	TreeElement root=new TreeElement("根",null);
	    	buildTreeForList(catagorys,root);
			return root.getChildren();
	    }
	    
	    private void buildTreeForList(List<ProductCategory> catagorys,TreeElement parent){
			if(catagorys.isEmpty())
				return;
			List<ProductCategory> recapt=new ArrayList();
			TreeElement temp;
			for(ProductCategory c:catagorys){
				if(isChinad(parent,c)){
					temp=new TreeElement(c.getName(), (Object)c);
					parent.addChild(temp);
				}else 
					recapt.add(c);
			}
			for(int i=0;i<parent.childCount();i++)
				buildTreeForList(recapt,(TreeElement) parent.getChild(i));
		}
	    
	    
	    private boolean isChinad(TreeElement parent,I_Category category1){
	    	I_Category category=(I_Category) parent.getTag();
	    	boolean isChinad=false;
			if(category==null){
				if(category1.getM_sParentID()==null)
					isChinad=true;
			}else if(category.getID().equalsIgnoreCase(category1.getM_sParentID()))
				isChinad=true;
			return  isChinad;
	    }
	
	
	    protected Handler mHandler1 = new Handler() {  
	       

			public void handleMessage (Message msg) {//此方法在ui线程运行   
	            switch(msg.what) {  
	            case MSG_LOAD_CATEGORY:  
	            	treeAdapter.setRootNode((List<TreeElement>) msg.obj);
	                break; 
	            case MSG_LOAD_PRODUCT:  
	            	listProducts=(List<ProductExt>)msg.obj;
	            	productAdapter.notifyDataSetChanged();
	                break;      
	            case MSG_FAILURE:  
	                Toast.makeText(getContext(), "执行出错了", Toast.LENGTH_LONG).show();  
	                break;
	            }  
	        }
	  }; 
	

	
	public void setOnBaseBeanSelectedListener(OnBaseBeanSelectedListener<Product> productSelectedListener){
		this.productSelectedListener=productSelectedListener;
	}
	
	 
    public boolean performItemClick(ProductExt product) {
        if (productSelectedListener != null) {
        	productSelectedListener.baseBeanSelected(product);
            return true;
        }
        return false;
    }

	
    /**
     * Set the listener that will receive notifications every time the list scrolls.
     *
     * @param l the scroll listener
     */
    public void setOnScrollListener(OnScrollListener l) {
        products.setOnScrollListener(l);
    }
    
	
	public void baseBeanSelected(final ProductCategory obj) {
		new Thread(){
			@Override
			public void run(){
				I_DataLogicSales dlSales=DataLogicPDA.getDLSales();
				try {
					List<ProductExt> shardProducts=dlSales.listWithParentClassAndKey(ProductExt.class.getName(), ProductCategory.class.getName(), obj.getID());
					mHandler1.obtainMessage(MSG_LOAD_PRODUCT,shardProducts).sendToTarget();//获取图片失败
				} catch (BasicException e) {
					mSuperHandler.obtainMessage(TicketManager.MSG_FAILURE).sendToTarget();//获取图片失败   
				}
			}
			}.start();
		
	}  
	
	private class GridViewAdapter extends BaseAdapter {   
        
        private Context context;   
           
        public GridViewAdapter(Context context) {   
            this.context = context;   
        }   
           
        int count = 100;   
  
        
        public int getCount() {   
            return listProducts==null?0:listProducts.size();   
        }   
  
        
        public Object getItem(int position) {   
            return position;   
        }   
  
       
        public long getItemId(int position) {   
            return position;   
        }   
  
       
        public View getView(int position, View convertView, ViewGroup parent) { 
        	ProductExt product=listProducts.get(position);
        	TextView result=null;
        	if(convertView!=null)
        		result =(TextView)convertView;   
        	else
                result = new TextView(context);   
            result.setText(product.getName());   
            result.setTextColor(Color.BLACK);   
            result.setTextSize(24);   
            result.setLayoutParams(new AbsListView.LayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT)));   
            result.setGravity(Gravity.CENTER);   
            result.setBackgroundColor(Color.WHITE); //设置背景颜色   
            return result;   
        }   
           
    }

	public void onItemClick(AdapterView<?> parent, View view, int position,
			long id) {
		ProductExt product=listProducts.get(position);
		performItemClick(product);
	}

	public void  setZoomClickListener(View.OnClickListener l){
		zoomImgBtn.setOnClickListener(l);
	}

}
